import $ from 'jQuery';
(function () {
    /**
     * 删除
     * @param params
     * @private
     */
    var _deleteOrganize = function (params) {
        IOT.confirm('你确定要删除吗？', () => {
            IOT.showOverlay('保存中，请稍等...');
            IOT.getServerData(URI.SYSTEM.ORGANIZE.DELETE, params, function (ret) {
                IOT.hideOverlay();
                if (ret && ret.code === 200) {
                    IOT.tips('删除成功！', 'success');
                    M.Table.refresh.all();
                    BootstrapDialog.closeAll();
                } else {
                    IOT.tips(ret.msg || '操作失败，请重试！', 'error');
                }
            });
            return false;
        }, null, 'warn');
    };
    /**
     * 修改
     * @param params
     * @private
     */
    var _modifyOrganize =  function (params) {
        // console.log(params);
        $('#upperOrg').val(params.userId);
        $('#upperNum').val(params.userName);
        $('#department').val(params.mobile);
        $('#order').val(params.email);
        layer.open({
            type: 1,
            title: ['修改组织机构'],
            area: ['400px', '350px'],
            content:$('#modifyOrg'),
            btn: ['确定', '取消'],
            yes: function(index, layero){
                layer.closeAll();
                IOT.showOverlay('保存中，请稍等...');
                $vue.organizeList.upper=$('#upperOrg').val();
                $vue.organizeList.upperNum=$('#upperNum').val();
                $vue.organizeList.department=$('#department').val();
                $vue.organizeList.order=$('#order').val();
                let params = $vue.$data.organizeList;
                console.log(params);
                IOT.getServerData(URI.SYSTEM.ORGANIZE.MODIFY , params, function (ret) {
                    IOT.hideOverlay();
                    if (ret && ret.code === 200) {
                        IOT.tips('保存成功！', 'success');
                        M.Table.refresh.all();
                        M.Page.emitPrePage();
                    } else {
                        IOT.tips(ret.msg || '操作失败，请重试！', 'error', 1000, null);
                    }
                });
                return false;
            },
        });

    };
    /**
     * 新增
     * @param params
     * @private
     */
    var _addOrganize = function(){
        $('#newupper').val(clickTreeNode.name);//替换为上级组织
        $('#newupperNum').val(clickTreeNode.pid);//替换为上级编码
        layer.open({
            type: 1,
            title: ['新增组织机构'],
            area: ['400px', '350px'],
            content:$('#addOrg'),
            btn: ['确定', '取消'],
            yes: function(index, layero){
                $vue.$data.neworganizeList.upper=$('#newupper').val();
                $vue.$data.neworganizeList.upperNum=$('#newupperNum').val();
                $vue.$data.neworganizeList.department=$('#newdepartment').val();
                $vue.$data.neworganizeList.order=$('#neworder').val();
                let params = $vue.$data.neworganizeList;
                layer.closeAll();
                IOT.showOverlay('保存中，请稍等...');
                IOT.getServerData(URI.SYSTEM.ORGANIZE.ADD , params, function (ret) {
                    IOT.hideOverlay();
                    if (ret && ret.code === 200) {
                        IOT.tips('保存成功！', 'success');

                        M.Table.refresh.all();
                        M.Page.emitPrePage();
                    } else {
                        IOT.tips(ret.msg || '操作失败，请重试！', 'error', 1000, null);
                    };
                    // $vue.organizeList.upper='';
                    // $vue.organizeList.upperNum='';
                    // $vue.organizeList.department='';
                    // $vue.organizeList.order='';
                });
                return false;
            },
        });
    };
    var formParams;//列表查询参数
    var clickTreeNode;//    选中的节点
    let $tree = null;
    let $vue = new Vue({
        el: '.organize-main-hook',
        data: {
            boxs: {
                box1: {show: true, hook: '.box1-hook', lock: true, url: '', params: {}},
                box2: {show: false, hook: '.box2-hook', url: '', params: {}},
                box3: {show: false, hook: '.box3-hook', url: '', params: {}},
                box4: {show: false, hook: '.box4-hook', url: '', params: {}}
            },
            organizeList:{
                'upper':'',//上级组织
                'upperNum':'',//上级编码
                'department':'',//部门名称
                'order':'',//排序号
            },
            neworganizeList:{
                'upper':'',//上级组织
                'upperNum':'',//上级编码
                'department':'',//部门名称
                'order':'',//排序号
            }
        },
        created: function () {
            M.Request.getRoleList(true, (roleList, ret) => {
                this.roleList = roleList;
            });
            /*树菜单*/
            let setting = {
                check: {
                    enable: false
                    // enable: true
                },
                view:{
                    selectedMulti: false,//不允许同时选中多个节点
                    showIcon :false,
                    showLine:false,
                    /*addDiyDom: function addDiyDom(treeId, treeNode){
                        var sObj = $("#" + treeNode.tId + "_a");
                        var addStr = "<span class='pallent_span'>托盘数："+treeNode.palletCount+"</span>";
                        sObj.append(addStr);
                        //超过部分用“...”显示
                        var spaceWidth = 5;
                        var switchObj = $("#" + treeNode.tId + "_switch"),
                            icoObj = $("#" + treeNode.tId + "_ico");
                        switchObj.remove();
                        icoObj.parent().before(switchObj);
                        var spantxt = $("#" + treeNode.tId + "_span").html();
                        if (spantxt.length > 15) {
                            spantxt = spantxt.substring(0, 15) + "...";
                            $("#" + treeNode.tId + "_span").html(spantxt);
                        }
                    }*/
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: 'id',
                        pIdKey: 'pid',
                        rootPId: 0,
                    }
                },
                callback: {
                    // onCheck:function zTreeOnCheck(event, treeId, treeNode){
                    //      console.log(treeNode);
                    // },
                    onClick:function onCheckTreeNode(event, treeId, treeNode){
                        console.log(treeNode);
                        clickTreeNode=treeNode;
                        formParams = treeNode;
                        $('.search-hook').trigger('click');
                        // $('.address').val(treeNode.name);
                        // $('.total-amount').val(treeNode.palletCount);
                        // $('.company-name').val(treeNode.companyName);
                    },
                    onRightClick:function zTreeOnRightClick(event, treeId, treeNode){
                        clickTreeNode=treeNode;
                        _addOrganize();
                    }
                }
            };
            IOT.getServerData(URI.SYSTEM.ORGANIZE.TREE, {}, (ret) => {
                console.log(ret.code);
                // console.log(ret);
                if (ret.code === 200) {
                    console.log(ret.data);
                    let treeList = ret.data;
                    $tree = $.fn.zTree.init($('#organize_tree'), setting, treeList);
                    var nodes = $tree.getNodes();
                    // console.log(nodes)
                    if (nodes.length>0) {
                        clickTreeNode=nodes[0];
                    }
                    // console.log(clickTreeNode);
                    $tree.expandAll(true);
                } else {
                    IOT.tips(ret.msg, 'error');
                }
            });
        },
        methods: {
            emitPage: function () {
                M.Page.load(this.boxs);
            },
            // 上一页
            prePage: function () {
                M.Page.prePage(this.boxs);
            },
            searchKey:function(){
                $('.search-hook').trigger('click');
            },
            // 触发刷新页(当前显示的页面)
            refreshPage: function () {
                M.Page.refreshPage(this.boxs);
            },
            //新增
            addOrganize:function(){
                _addOrganize();
            }
        },
        mounted: function () {
            let thiz = this;
            this.$nextTick(() => {
                let tableHookName = '.organize-table-hook';
                let $accountBox = $('.organize-hook');
                var $form = $accountBox.find('.form-hook');
                // 查询
                $form.off('submit').on('submit', function () {
                    formParams = $form.serializeJson();
                    $(tableHookName).bootstrapTable('onCustomSearch');
                    return false;
                });
                var $tableHook = $accountBox.find(tableHookName).bootstrapTable({
                    scrollbar: 'organize-table-body',
                    striped: true, // 设置为 true 会有隔行变色效果
                    pagination: true, // true 显示分页
                    paginationDetail: true, // 分页详情
                    sidePagination: 'server', // 服务器端
                    method: 'post',
                    url: URI.SYSTEM.ORGANIZE.LIST,
                    debug: false,
                    cache: false,
                    pageNumber: 1,
                    pageSize: 10,
                    pageList: [10, 20, 50, 100],
                    smartDisplay:false,
                    // fixedColumns: true,
                    customButton: '',
                    customQueryParams: function (params) {
                        var queryParams = $.extend({}, params, formParams);
                        //console.log(queryParams);
                        return queryParams;
                    },
                    onLoadSuccess: function (data) {
                        //console.log(JSON.stringify(data));
                    },
                    onLoadError: function (status, xhr) {
                    },
                    onCheckAll: function (rows) {

                    },
                    columns: [
                        // {
                        //     field: '', checkbox: true, align: 'center', fixedLeft: true, width: 60,
                        //     events: {
                        //         'change .checkbox-hook': function (e, value, row, index) {
                        //             //console.log('复选框: ' + value);
                        //         }
                        //     }
                        // },
                        {
                            field: 'mobile', title: '组织编码', align: 'center', fixedLeft: true,tips:true
                        },
                        {
                            field: 'userName', title: '组织名称', align: 'center', fixedLeft: true,tips:true
                        },
                        {
                            field: 'gender', title: '排序号', align: 'center', fixedLeft: true,width:80,
                        },
                        {
                            field: 'companyName', title: '上级机构', align: 'center', fixedLeft: true,tips:true
                        },
                        {
                            field: 'operate', title: '操作', align: 'center', fixedLeft: true, width: 180,
                            events: {
                                'click .modify-account': function (e, value, rowData, index) {
                                    _modifyOrganize(rowData);
                                    return false;
                                    IOT.setSessionStore(URI.SYSTEM.ORGANIZE.PAGE, JSON.stringify(rowData));
                                    return false;
                                },
                                'click .delete-account': function (e, value, row, index) {
                                    _deleteOrganize(row);
                                    return false;
                                },

                            },
                            formatter: function (value, row, index) {
                                let html = [];
                                if (M.Authority.checkAuthority('account-modify')) {
                                    html.push('<a class="modify-account operate">修改</a>');
                                }
                                if (!row.admin) {
                                    if (M.Authority.checkAuthority('account-delete')) {
                                        html.push('<a class="delete-account operate">删除</a>');
                                    }
                                }
                                return html.join('');
                            }
                        }
                    ]
                });
            });
        }
    });
})();